﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp {
    
    public class MyDisposableType : IDisposable {
        private bool _disposed = false;

        // This public method can be called to deterministically close
        //   the resource
        // This method implements IDisposable's Dispose
        public void Dispose() {
            // Call the method that actually does the cleanup
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // When garbage collected, this Finalize method runs to dispose
        //   the resource
        ~MyDisposableType() {
            // Call the method that actually does the cleanup
            Dispose(false);
        }
        
        // This is the common method that does the actual cleanup
        // Finalize and Dispose call this method
        // Because this class isn't sealed, this method is
        //   protected and virtual
        // If this class were sealed, this method should be private
        protected virtual void Dispose(bool disposing) {
            // Be sure we have not already been disposed
            if (!_disposed) {

                if (disposing) {
                    // The object is being explicitly disposed/closed, not
                    //   finalized
                    // It is therefore safe for code in this if statement
                    //   to access fields that reference other objects
                    //   because the Finalize method of these other objects
                    //   hasn't yet been called

                    // Dispose *managed* resources here
                    Console.WriteLine("Disposing managed resources...");
                }

                // Clean up *unmanaged* resources here
                Console.WriteLine("Disposing unmanaged resources...");
            }
            _disposed = true;
        }
    }
}
